package com.zilue.payment.gateway.manage;

import com.zilue.payment.gateway.config.ConfigHelper;
import com.zilue.payment.gateway.domain.CorpDO;
import com.zilue.payment.gateway.paramter.PublicParameter;
import com.zilue.security.util.rsa.RSAPublicKeyStaticUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * Created by zilue on 2017/3/29.
 */
@Service
public class SignManager extends BaseManager {
    private Logger logger = Logger.getLogger(OrderRefundManager.class);
    public static final String YUANTU_PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJ+rUnQm9fLJ2XWhiEcacW0K56VTpYpyu0ml8GGhodT3GKf/mAytNrYrWTyQaLR3a0FkIiIIPPgHexrLCcGHnLe+Ovucu1YyJ9cOkVSw0zeXdxBk2MqFjc1/qRruwFTzwyqAgKBfRBddudlautj+GJQkRspdGfn+YVT8aaFc6+ZZAgMBAAECgYA/tHc9aJ4QtIBS8pQQ6nf+7a7mw6z0xDn9dHuoOHj9I2lu/geIZ0PBAyKji2p7NnpQqMcFlQveWf2//upxkM3x0EeHQABKxsLm3Dvlukkt6CI7vSso9scwFUWphxDFrvhwE3DqnoPTa6PzGJGwyg5LmFGFE2bdVS31MdsYpUyWQQJBANCTOCMk0siudSM5ZPCVLboghQ8KiiMWTwR7YYbGKlmvrR+fBf4ndsoJ4nFg075zt68c8pOvua8Tup2yywyuZcUCQQDD+WGTSFHDpaiTUfb5d+DjfC4O0PjRNu11/f91lT1I1YGR5uirTJ7b6F6lUfCc5Z5SVnk9zd8SI7dF7AiN1FuFAkAOaEz1aILC6AIhZ8KIN9XLyJlIW7MFD3Jv3dHzzFZ6kX8E8ygn0TQMarhgmo6l1jp29ynud7H83QEECaiq/JT9AkA2ybd/x44kVmHkndugLuWOc58kwUNuqh6FCDetFcYGYLpSoe2WRlt7O2GKcngERSWX+1j18GJW3elVAQH7NM1JAkEAscdK82K7TQSQnh3aOO2jhCTsYqbfTp1pVlb8BqNTBDJQfwrRJmKQStDhFckMbounwmtCtvsXlYEJ3vSaxp1JKg==";
    public static final String YUANTU_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfq1J0JvXyydl1oYhHGnFtCuelU6WKcrtJpfBhoaHU9xin/5gMrTa2K1k8kGi0d2tBZCIiCDz4B3saywnBh5y3vjr7nLtWMifXDpFUsNM3l3cQZNjKhY3Nf6ka7sBU88MqgICgX0QXXbnZWrrY/hiUJEbKXRn5/mFU/GmhXOvmWQIDAQAB";

    public static final int AUTH_SUCCESS = 1;
    public static final int AUTH_FAILED = 0;
    public static final int NO_APPID = -1;

    public int verifyRequest(PublicParameter publicParameter) {
        CorpDO corpDO = queryCorpByAppid(publicParameter.getAppid());
        if (corpDO == null) {
            return NO_APPID;
        }
        if (!ConfigHelper.PayGatewayAuth)
            return AUTH_SUCCESS;
        String publicKey = corpDO.getPublicKey();
        if (StringUtils.isEmpty(publicKey)) {
            logger.warn("商户公钥尚未配置。商户ID" + publicParameter.getAppid());
            return AUTH_FAILED;
        }
        if (StringUtils.isEmpty(publicParameter.getSign())) {
            logger.warn("本次请求无签名信息。商户ID" + publicParameter.getAppid());
            return AUTH_FAILED;
        }
        Map<String, String> paramterMap = publicParameter.getParamterMap();

        boolean verify = RSAPublicKeyStaticUtil.verifyDigitalSignature(paramterMap, publicKey);
        if (verify)
            return AUTH_SUCCESS;
        else
            return AUTH_FAILED;
    }

}
